import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:intl/intl.dart';
import 'package:kq_flutter_tv_widgets/config/kq_global.dart';
import 'package:kq_flutter_tv_widgets/resources/images.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../resources/kq_theme_colors.dart';
import '../divider/kq_divider.dart';

/// 时间选择模式，单个时间，时间范围
enum KQSelectMode { single, range }

// ignore: must_be_immutable
class KqCalendar extends StatefulWidget {
  /// 语言:中文：'zh';英文：'en'
  final String? locale;

  ///日历选择模式：默认：可选范围
  final KQSelectMode? selectMode;

  ///自定义头部
  final Widget? calendarCustomHeader;

  ///自定义尾部
  final Widget? calendarCustomFooter;

  final DateTime? selectedDay;
  DateTime? rangeStart;
  DateTime? rangeEnd;

  /// 限制时间 默认：2010-01-01 至 2040-01-01
  final DateTime? limitStartTime;

  /// 限制时间 默认：2010-01-01 至 2040-01-01
  final DateTime? limitEndTime;

  /// 初始选中日期
  DateTime? focusedDay;

  ///日期回调
  /// 选单个回调
  final Function(DateTime date)? selectedSingleDateCallback;

  /// 选范围回调
  final Function(DateTime? startDate, DateTime? endDate)?
      selectedRangeDateCallback;

  KqCalendar(
      {this.locale = 'zh',
      this.selectMode = KQSelectMode.range,
      this.calendarCustomHeader,
      this.calendarCustomFooter,
      this.selectedDay,
      this.rangeStart,
      this.rangeEnd,
      this.limitStartTime,
      this.limitEndTime,
      this.focusedDay,
      this.selectedSingleDateCallback,
      this.selectedRangeDateCallback,
      super.key});

  @override
  State<KqCalendar> createState() => _KqCalendarState();
}

class _KqCalendarState extends State<KqCalendar> {
  // DateTime? _startDate;
  // DateTime? _endDate;

  CalendarFormat _calendarFormat = CalendarFormat.month;
  RangeSelectionMode _rangeSelectionMode = RangeSelectionMode
      .toggledOn; // Can be toggled on/off by longpressing a date
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  DateTime? _rangeStart;
  DateTime? _rangeEnd;

  @override
  void initState() {
    super.initState();
    _selectedDay = widget.selectedDay;
    _rangeStart = widget.rangeStart;
    _rangeEnd = widget.rangeEnd;
    if (widget.focusedDay != null) {
      _focusedDay = widget.focusedDay!;
    }
    if (widget.selectMode == KQSelectMode.range) {
      _selectedDay = null;
    }
  }

  @override
  void didUpdateWidget(covariant KqCalendar oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.selectMode == KQSelectMode.single) {
      if (oldWidget.focusedDay != widget.focusedDay) {
        if (widget.focusedDay != null) {
          setState(() {
            _focusedDay = widget.focusedDay!;
          });
        }
      }
    } else {
      setState(() {
        _rangeStart = widget.rangeStart;
        _rangeEnd = widget.rangeEnd;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        widget.calendarCustomHeader ?? const SizedBox(),
        widget.calendarCustomHeader != null
            ? const KqDivider()
            : const SizedBox(),
        Container(
          color: KqThemeColors.bgDialog,
          child: widget.selectMode == KQSelectMode.single
              ? TableCalendar(
                  locale: widget.locale == 'zh' ? 'zh_CN' : 'en_US',
                  firstDay: widget.limitStartTime ?? DateTime.utc(2010, 01, 01),
                  lastDay: widget.limitEndTime ?? DateTime.utc(2040, 01, 01),
                  focusedDay: _focusedDay,
                  daysOfWeekHeight: 44.r,
                  pageAnimationEnabled: false,
                  rowHeight: 65.r,
                  headerStyle: HeaderStyle(
                      leftChevronIcon: Image.asset(
                        Images.commonIcXiala24Left,
                        width: 44.r,
                        height: 44.r,
                        package: KqGlobal.packageName,
                      ),
                      rightChevronIcon: Image.asset(Images.commonIcXiala24Right,
                          width: 44.r,
                          height: 44.r,
                          package: KqGlobal.packageName)),
                  calendarStyle: CalendarStyle(
                      isTodayHighlighted: false,
                      markersAutoAligned: false,
                      cellMargin: EdgeInsets.symmetric(horizontal: 55.r),
                      markerDecoration: const BoxDecoration(color: KqThemeColors.bgBlue, shape: BoxShape.rectangle),
                      defaultDecoration: const BoxDecoration(shape: BoxShape.rectangle),
                      selectedDecoration: const BoxDecoration(color: KqThemeColors.bgBlue, shape: BoxShape.rectangle)),
                  selectedDayPredicate: (day) {
                    if (_selectedDay != null) {
                      return isSameDay(day, _selectedDay);
                    }
                    return false;
                  },
                  calendarBuilders: CalendarBuilders(
                    headerTitleBuilder: (context, day) {
                      String yearString = '年';
                      String monthString = '月';
                      if (widget.locale != 'zh') {
                        yearString = '-';
                        monthString = '';
                      }
                      return Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '${day.year}$yearString${day.month}$monthString',
                            style: TextStyle(
                                fontSize: 32.sp,
                                color: KqThemeColors.textBlack85),
                          )
                        ],
                      );
                    },
                    outsideBuilder: (context, day, focusedDay) {
                      return SizedBox(
                        width: 65.r,
                        height: 65.r,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textBlack25),
                          ),
                        ),
                      );
                    },
                    defaultBuilder: (context, day, focusedDay) {
                      return SizedBox(
                        width: 65.r,
                        height: 65.r,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textBlack85),
                          ),
                        ),
                      );
                    },
                    selectedBuilder: (context, day, focusedDay) {
                      return Container(
                        color: KqThemeColors.bgBlue,
                        width: 65.r,
                        height: 65.r,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textWhite),
                          ),
                        ),
                      );
                    },
                    withinRangeBuilder: (context, day, focusedDay) {
                      return SizedBox(
                        width: 65.r,
                        height: 65.r,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textBlack85),
                          ),
                        ),
                      );
                    },
                    singleMarkerBuilder: (context, day, event) {
                      return SizedBox(
                        width: 65.r,
                        height: 65.r,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textBlack85),
                          ),
                        ),
                      );
                    },
                    disabledBuilder: (context, day, focusedDay) {
                      return SizedBox(
                        width: 65.r,
                        height: 65.r,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textBlack25),
                          ),
                        ),
                      );
                    },
                    dowBuilder: (context, day) {
                      return Center(
                        child: Text(
                          getDowBuilderContent(day),
                          style: TextStyle(
                              fontSize: 24.sp,
                              color: KqThemeColors.textBlack65),
                        ),
                      );
                    },
                  ),
                  onDaySelected: (selectedDay, focusedDay) {
                    setState(() {
                      _focusedDay = selectedDay;
                      _selectedDay = selectedDay;
                    });
                    widget.selectedSingleDateCallback?.call(selectedDay);
                  },
                  onPageChanged: (focusedDay) {
                    _focusedDay = focusedDay;
                  },
                  availableCalendarFormats: const {
                      CalendarFormat.month: 'Month'
                    })
              : TableCalendar(
                  locale: widget.locale == 'zh' ? 'zh_CN' : 'en_US',
                  firstDay: widget.limitStartTime ?? DateTime.utc(2010, 01, 01),
                  lastDay: widget.limitEndTime ?? DateTime.utc(2040, 01, 01),
                  focusedDay: _focusedDay,
                  selectedDayPredicate: (day) {
                    return isSameDay(_selectedDay, day);
                  },
                  rangeStartDay: _rangeStart,
                  rangeEndDay: _rangeEnd,
                  daysOfWeekHeight: 44.r,
                  pageAnimationEnabled: false,
                  rowHeight: 65.r,
                  rangeSelectionMode: _rangeSelectionMode,
                  headerStyle: HeaderStyle(
                      headerPadding: const EdgeInsets.symmetric(vertical: 0.0),
                      leftChevronIcon: Image.asset(
                        Images.commonIcXiala24Left,
                        width: 44.r,
                        height: 44.r,
                        package: KqGlobal.packageName,
                      ),
                      rightChevronIcon: Image.asset(Images.commonIcXiala24Right,
                          width: 44.r,
                          height: 44.r,
                          package: KqGlobal.packageName)),
                  calendarStyle: CalendarStyle(
                      isTodayHighlighted: false,
                      cellMargin: EdgeInsets.symmetric(horizontal: 55.r),
                      rangeHighlightColor: KqThemeColors.bgBlack05,
                      markerDecoration: const BoxDecoration(
                          color: KqThemeColors.bgBlue,
                          shape: BoxShape.rectangle),
                      defaultDecoration:
                          const BoxDecoration(shape: BoxShape.rectangle),
                      rangeStartDecoration: const BoxDecoration(
                          color: KqThemeColors.bgBlue,
                          shape: BoxShape.rectangle),
                      rangeEndDecoration: const BoxDecoration(color: KqThemeColors.bgBlue, shape: BoxShape.rectangle)),
                  onDaySelected: (selectedDay, focusedDay) {
                    if (!isSameDay(_selectedDay, selectedDay)) {
                      setState(() {
                        _selectedDay = selectedDay;
                        _focusedDay = focusedDay;
                        _rangeStart = null; // Important to clean those
                        _rangeEnd = null;
                        _rangeSelectionMode = RangeSelectionMode.toggledOff;
                      });
                    }
                  },
                  onRangeSelected: (start, end, focusedDay) {
                    setState(() {
                      _selectedDay = null;
                      _focusedDay = focusedDay;
                      _rangeStart = start;
                      _rangeEnd = end;
                      _rangeSelectionMode = RangeSelectionMode.toggledOn;
                    });
                    widget.selectedRangeDateCallback?.call(start, end);
                  },
                  onFormatChanged: (format) {
                    if (_calendarFormat != format) {
                      setState(() {
                        _calendarFormat = format;
                      });
                    }
                  },
                  onPageChanged: (focusedDay) {
                    _focusedDay = focusedDay;
                  },
                  calendarBuilders: CalendarBuilders(
                    headerTitleBuilder: (context, day) {
                      String yearString = '年';
                      String monthString = '月';
                      if (widget.locale != 'zh') {
                        yearString = '-';
                        monthString = '';
                      }
                      return Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '${day.year}$yearString${day.month}$monthString',
                            style: TextStyle(
                                fontSize: 32.sp,
                                color: KqThemeColors.textBlack85),
                          )
                        ],
                      );
                    },
                    defaultBuilder: (context, day, focusedDay) {
                      return SizedBox(
                        width: 65.r,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textBlack85),
                          ),
                        ),
                      );
                    },
                    outsideBuilder: (context, day, focusedDay) {
                      return SizedBox(
                        width: 65.r,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textBlack25),
                          ),
                        ),
                      );
                    },
                    withinRangeBuilder: (context, day, focusedDay) {
                      return SizedBox(
                        width: 65.r,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textBlack85),
                          ),
                        ),
                      );
                    },
                    disabledBuilder: (context, day, focusedDay) {
                      return SizedBox(
                        width: 65.r,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textBlack25),
                          ),
                        ),
                      );
                    },
                    rangeStartBuilder: (context, day, focusedDay) {
                      return Container(
                        width: 65.r,
                        color: KqThemeColors.bgBlue,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textWhite),
                          ),
                        ),
                      );
                    },
                    rangeEndBuilder: (context, day, focusedDay) {
                      return Container(
                        width: 65.r,
                        color: KqThemeColors.bgBlue,
                        child: Center(
                          child: Text(
                            day.day.toString(),
                            style: TextStyle(
                                fontSize: 28.sp,
                                color: KqThemeColors.textWhite),
                          ),
                        ),
                      );
                    },
                    dowBuilder: (context, day) {
                      return Center(
                        child: Text(
                          getDowBuilderContent(day),
                          style: TextStyle(
                              fontSize: 24.sp,
                              color: KqThemeColors.textBlack65),
                        ),
                      );
                    },
                  ),
                  availableCalendarFormats: const {CalendarFormat.month: 'Month'}),
        ),
        widget.calendarCustomFooter != null
            ? const KqDivider()
            : const SizedBox(),
        widget.calendarCustomFooter ?? const SizedBox(),
        widget.calendarCustomFooter != null
            ? const KqDivider()
            : const SizedBox(),
        // Row(
        //   mainAxisAlignment: MainAxisAlignment.end,
        //   crossAxisAlignment: CrossAxisAlignment.center,
        //   children: [
        //     Container(
        //       height: 54.r,
        //       padding: const EdgeInsets.fromLTRB(0, 8, 16, 8),
        //       child: KqOutlineButton(
        //         title: KqIntl.currentResource.confirm,
        //         bgColor: KqThemeColors.bgBlue,
        //         borderColor: KqThemeColors.bgBlue,
        //         textColor: KqThemeColors.textWhite,
        //         fontSize: 14.sp,
        //         onTap: (disabled) {
        //           // if (_startDate != null && _endDate != null) {
        //           //   widget.selectedDateCallback(_startDate, _endDate);
        //           // } else if (_startDate != null) {
        //           //   widget.selectedDateCallback(_startDate, _startDate);
        //           // } else if (_endDate != null) {
        //           //   widget.selectedDateCallback(_endDate, _endDate);
        //           // }
        //         },
        //       ),
        //     )
        //   ],
        // )
      ],
    );
  }

  String getDowBuilderContent(DateTime day) {
    if (day.weekday == DateTime.sunday) {
      ///星期日
      return '日';
    } else if (day.weekday == DateTime.saturday) {
      ///星期六
      return '六';
    } else if (day.weekday == DateTime.friday) {
      ///星期五
      return '五';
    } else if (day.weekday == DateTime.thursday) {
      ///星期四
      return '四';
    } else if (day.weekday == DateTime.wednesday) {
      ///星期三
      return '三';
    } else if (day.weekday == DateTime.tuesday) {
      ///星期二
      return '二';
    } else if (day.weekday == DateTime.monday) {
      ///星期一
      return '一';
    }
    return DateFormat.E().format(day);
  }
}
